package com.employment.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;

/**
 * WebSocket配置类 - 支持JDK 21虚拟线程
 * 
 * @author employment
 * @since 2024-01-01
 */
@Configuration
@EnableAsync
public class WebSocketConfig {
    
    /**
     * ServerEndpointExporter 作用
     * 
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
    
    /**
     * 配置WebSocket异步任务执行器 - 使用虚拟线程
     * JDK 21的虚拟线程将自动被Spring Boot利用
     */
    @Bean("websocketTaskExecutor")
    public Executor websocketTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 虚拟线程下可以设置更大的线程池大小
        executor.setCorePoolSize(50);
        executor.setMaxPoolSize(200);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("WebSocket-VirtualThread-");
        executor.initialize();
        return executor;
    }
}